package handle

import (
	"fmt"

	"github.com/gin-gonic/gin"

	"git.internal.yunify.com/benchmark/benchmark/pkg/app"
	"git.internal.yunify.com/benchmark/benchmark/pkg/global"
	"git.internal.yunify.com/benchmark/benchmark/pkg/registry"
	"git.internal.yunify.com/benchmark/benchmark/pkg/util/mdtemplate"
)

func Status(ctx *gin.Context) {
	var (
		out                    string
		err                    error
		registryServiceColumns [][]string
	)

	defer func() {
		if err != nil {
			ctx.AbortWithError(500, err)
		}
	}()

	//注册中心数据
	if registryServiceColumns, err = registryService(); err != nil {
		return
	}
	out += mdtemplate.SliceToMd("注册中心服务信息", registryServiceColumns)

	//版本信息
	out += mdtemplate.SliceToMd("应用版本信息", app.VersionColumns())

	ctx.Writer.Write([]byte(mdtemplate.MdWithCss(out)))
	return
}

//registryService 服务状态
func registryService() (column [][]string, err error) {
	var (
		services []*registry.Service
	)

	column = append(column, []string{"服务名称", "节点"})
	if global.Registry() == nil {
		return
	}

	if services, err = global.Registry().ListServices(); err != nil {
		return
	}

	for _, v := range services {
		nodes := ""
		for _, v1 := range v.Nodes {
			nodes += fmt.Sprintf("Id:%s,Address:%s<br>", v1.Id, v1.Address)
		}

		column = append(column, []string{v.Name, nodes})

	}

	return
}
